package com.solt.prism.core.utils;

import java.sql.SQLException;
import java.util.List;

import com.solt.prism.core.conf.PrismConfiguration;
import com.solt.prism.core.entity.News;
import com.solt.prism.core.similar.DocSimilar;
import com.solt.prism.dao.imp.JosDao;

public class NewsPersistencerImpl implements NewsPersistencer {
	private JosDao josDao;
	private RelationNews relation;
	public NewsPersistencerImpl() {
		try {
			josDao = new JosDao();
			boolean train = PrismConfiguration.getInstance().getBoolean(PrismConstants.NEWS_RELATE_TRAIN, false);
			relation = train ? RelationNewsTrain.getInstance() : RelationNewsImpl.getInstance();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Override
	public synchronized void store(News news) {
		try {
			 List<DocSimilar> relateNews = relation.relateNews(news);
			if (relateNews != null) {
				int newsID = josDao.insertNews(news, relateNews);
				if (newsID != -1) {
					relation.storeCurrNewsWithID(newsID);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sync() {
		relation.sync();
	}

	@Override
	public void close() {
		relation.close();
	}

}
